/**
 * 
 */
package arisufascion.com.activity;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import arisufascion.com.AbstractActivity;
import arisufascion.com.R;
import arisufascion.com.adapter.GalleryImageColorAdapter;
import arisufascion.com.constant.Constants;
import arisufascion.com.constant.WriteLog;
import arisufascion.com.db.ProductDataSource;
import arisufascion.com.model.Attribute;
import arisufascion.com.model.Product;
import arisufascion.com.tabs.BadgeTabManager;

import com.androidquery.AQuery;

/**
 * @author Kelvin
 * 
 */
public class Activity_Detail extends AbstractActivity implements
		OnClickListener {
	private TextView txt_product_name, txt_product_s_desc, txt_product_price,
			txt_product_desc;
	private ImageView iv_big, iv_thumb1, iv_thumb2, iv_thumb3;
	private ImageButton imageButtonRate;
	private EditText editext_quantity;
	private Product product;
	private AQuery aq;
	private int colorId = 0;
	private int position_color = 0;
	private ImageButton btn_add;

	private ProductDataSource dbAdapter;
	private List<Attribute> attributes = new ArrayList<Attribute>();
	private Gallery galleryColor;
	private GalleryImageColorAdapter gallerAdatper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_productdetail);
		
		findViewById(R.id.btn_menu).setOnClickListener(onClick);
		findViewById(R.id.btn_privacy).setOnClickListener(onClick);
		findViewById(R.id.btn_wholesale).setOnClickListener(onClick);
		findViewById(R.id.btn_shipping).setOnClickListener(onClick);
		

		btn_add = (ImageButton) findViewById(R.id.btn_add);
		galleryColor = (Gallery) findViewById(R.id.galleryColor);

		initView();
		aq = new AQuery(self);

		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			product = bundle.getParcelable(PRODUCT);
			// set data for gallery color image
			attributes = product.getAttribute();
			gallerAdatper = new GalleryImageColorAdapter(self, attributes);
			galleryColor.setSpacing(3);
			galleryColor.setAdapter(gallerAdatper);
			// clicklistener for Gallery
			galleryColor.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View v,
						int position, long id) {
					// show the selected Image
					colorId = attributes.get(position).getColorid();
					position_color = position;
					Attribute at=attributes.get(position);
					
					String url = String
							.format(Constants.SERVER_URL_IMAGES, String
									.valueOf(attributes.get(position)
											.getPhoto()));

					aq.id(iv_big).image(url, true, true, 0,
							R.drawable.icon_logo);
					
					if(at.getQuantity()<1){
						btn_add.setVisibility(GONE);
					}else{
						btn_add.setVisibility(VISIBLE);
						
					}

				}
			});

			txt_product_name.setText(product.getProduct_name());
			txt_product_desc.setText(Html.fromHtml(product.getProduct_desc()));
			txt_product_s_desc.setText(Html.fromHtml(product
					.getProduct_s_desc()));
			txt_product_price
					.setText( "$"+product.getProduct_price());
			String url_img_big;

			String url_img_thumb1;

			String url_img_thumb2;

			String url_img_thumb3;

			for (int i = 0; i < product.getImages().size(); i++) {

				WriteLog.d("Kelvin-==========================", product
						.getImages().get(i).getFile_url());
				switch (i) {
				case 0:
					url_img_big = String.format(Constants.SERVER_URL_IMAGES,
							product.getImages().get(i).getFile_url());
					aq.id(iv_big).image(url_img_big, true, true, 0,
							R.drawable.icon_logo);

					break;
				case 1:
					url_img_thumb1 = String.format(Constants.SERVER_URL_IMAGES,
							product.getImages().get(0).getFile_url());
					aq.id(iv_thumb1).image(url_img_thumb1, true, true, 0,
							R.drawable.icon_logo);

					break;
				case 2:
					url_img_thumb2 = String.format(Constants.SERVER_URL_IMAGES,
							product.getImages().get(1).getFile_url());
					aq.id(iv_thumb2).image(url_img_thumb2, true, true, 0,
							R.drawable.icon_logo);
					break;
				case 3:
					url_img_thumb3 = String.format(Constants.SERVER_URL_IMAGES,
							product.getImages().get(2).getFile_url());
					aq.id(iv_thumb3).image(url_img_thumb3, true, true, 0,
							R.drawable.icon_logo);
					break;
				default:
					break;
				}
			}

		}

	}

	public void initView() {
		iv_big = (ImageView) findViewById(R.id.iv_big);
		iv_thumb1 = (ImageView) findViewById(R.id.iv_thumb1);
		iv_thumb2 = (ImageView) findViewById(R.id.iv_thumb2);
		iv_thumb3 = (ImageView) findViewById(R.id.iv_thumb3);
		imageButtonRate = (ImageButton) findViewById(R.id.imageButtonRate);

		txt_product_name = (TextView) findViewById(R.id.txt_product_name);
		txt_product_s_desc = (TextView) findViewById(R.id.txt_product_s_desc);
		txt_product_price = (TextView) findViewById(R.id.txt_product_price);
		txt_product_desc = (TextView) findViewById(R.id.txt_product_desc);
		editext_quantity = (EditText) findViewById(R.id.editext_quantity);

		btn_add.setOnClickListener(this);
		iv_thumb1.setOnClickListener(this);
		iv_thumb2.setOnClickListener(this);
		iv_thumb3.setOnClickListener(this);

	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		
		case R.id.btn_add:

			if (editext_quantity.getText().toString().length() > 0) {

				if (Integer.parseInt(editext_quantity.getText().toString()) > 0) {
					
				
//				step 1
				if(product.getAttribute().size()>0){
//					step2
					if (product.getAttribute().get(position_color).getQuantity() < Integer
							.parseInt(editext_quantity.getText().toString())) {

						editext_quantity.setError(Html
								.fromHtml("<font color='red'>Max quantity is "
										+ product.getAttribute().get(0)
												.getQuantity() + "</font>"));
					} else {
						// editext_quantity.getText();
						dbAdapter = new ProductDataSource(self);
						dbAdapter.open();
						
						
						// insert array images of product on database local
						for (int i = 0; i < product.getImages().size(); i++) {
							dbAdapter.createImagesProduct(product.getImages()
									.get(i).getFile_url(), Integer
									.parseInt(product
											.getVirtuemart_product_id()));
						}
						for (int k = 0; k < product.getAttribute().size(); k++) {
							dbAdapter.insertAttribute(product.getAttribute().get(k), Integer.parseInt(product.getVirtuemart_product_id()));
						}
						
						
						Attribute attribute=dbAdapter.getAllAttributes(Integer.parseInt(product.getVirtuemart_product_id())).get(position_color);

						Product pr = dbAdapter.getProduct(product
								.getVirtuemart_product_id(),attribute.getColorid());

						if (pr.getVirtuemart_product_id() == null) {

							// insert product to database local for use in the
							// screen shopping cart
							dbAdapter.InsertdatatoTable(Integer.parseInt(product
									.getVirtuemart_product_id().toString()),
									txt_product_name.getText().toString(),
									txt_product_desc.getText().toString(),
									txt_product_s_desc.getText().toString(), Float
											.parseFloat(txt_product_price.getText()
													.toString().replace("$", "")),
													attribute
											.getColorid(),attribute.getQuantity(),attribute.getPhoto(),
									Integer.parseInt(editext_quantity.getText()
											.toString()), attribute.getSizeid());
							

							
						} else {
							if (pr.getQuantity()
									+ Integer.parseInt(editext_quantity.getText()
											.toString()) > product.getAttribute()
									.get(position_color).getQuantity()) {
								editext_quantity
										.setError(Html
												.fromHtml("<font color='red'>Max quantity is "
														+ product.getAttribute()
																.get(0)
																.getQuantity()
														+ "</font>"));

							} else {
								product.setQuantity(product.getQuantity()
										+ Integer.parseInt(editext_quantity
												.getText().toString()));
								
								dbAdapter.updateProduct(product);
							}

						}
					}
				}else{

					dbAdapter = new ProductDataSource(self);
					dbAdapter.open();
					
					Product pr = dbAdapter.getProduct(product
							.getVirtuemart_product_id(),product.getColor_id());
					
					// insert product to database local for use in the
					// screen shopping cart
					// editext_quantity.getText();
					
					if (pr.getVirtuemart_product_id() == null) {

						try {
							dbAdapter.InsertdatatoTable(Integer.parseInt(product
									.getVirtuemart_product_id().toString()),
									txt_product_name.getText().toString(),
									txt_product_desc.getText().toString(),
									txt_product_s_desc.getText().toString(), Float
											.parseFloat(txt_product_price.getText()
													.toString().replace("$", "")),
									product.getAttribute().get(position_color).getColorid(),product.getAttribute().get(position_color).getQuantity(), "",
									Integer.parseInt(editext_quantity.getText()
											.toString()), 0);

							// insert array images of product on database local
							for (int i = 0; i < product.getImages().size(); i++) {
								dbAdapter.createImagesProduct(product.getImages()
										.get(i).getFile_url(), Integer
										.parseInt(product
												.getVirtuemart_product_id()));
							}
						} catch (Exception e) {
							// TODO: handle exception
						}
						
					}else{
						
						if(product.getQuantity()>pr.getQuantity()+ Integer.parseInt(editext_quantity
								.getText().toString())){
							
							product.setQuantity(product.getQuantity()
									+ Integer.parseInt(editext_quantity
											.getText().toString()));
							
							dbAdapter.updateProduct(product);
						}else{
							Toast.makeText(self, 	Html.fromHtml("<font color='red'>Max quantity is "
									+ pr.getQuantity()
							+ "</font>"), Toast.LENGTH_SHORT).show();
						
						}
						
						
						
					//	update item shopping cart
						dbAdapter = new ProductDataSource(self);
						dbAdapter.open();
						
						int index=0 ;
						for (int i = 0; i < dbAdapter.getProducts().size(); i++) {
							index+=dbAdapter.getProducts().get(i).getQuantity();
						}
						
					    BadgeTabManager.getInstance().setBadgeAtIndex(index, 1);
					    
						break;
					}
						
				}
			}else{
				editext_quantity.setError(Html
						.fromHtml("<font color='red'>Minim quantity is 1"
								+ "</font>"));
			}
				
			} else {
				editext_quantity.setError(Html
						.fromHtml("<font color='red'>Please enter quantity"
								+ "</font>"));
			}
//			update item shopping cart
			dbAdapter = new ProductDataSource(self);
			dbAdapter.open();
			
			int index=0 ;
			for (int i = 0; i < dbAdapter.getProducts().size(); i++) {
				index+=dbAdapter.getProducts().get(i).getQuantity();
			}
			
		    BadgeTabManager.getInstance().setBadgeAtIndex(index, 1);
		    

			break;

		case R.id.iv_thumb1:
			if(product.getImages().size()>=1){
				String url_thumb1 = String.format(Constants.SERVER_URL_IMAGES,
						product.getImages().get(0).getFile_url());
				aq.id(iv_big)
						.image(url_thumb1, true, true, 0, R.drawable.icon_logo);
			}

			break;
		case R.id.iv_thumb2:
			if(product.getImages().size()>=2){
			String url_thumb2 = String.format(Constants.SERVER_URL_IMAGES,
					product.getImages().get(1).getFile_url());
			WriteLog.d(TAG, url_thumb2);
			aq.id(iv_big)
					.image(url_thumb2, true, true, 0, R.drawable.icon_logo);
			}
			break;
		case R.id.iv_thumb3:
			if(product.getImages().size()>=3){
			String url_thumb3 = String.format(Constants.SERVER_URL_IMAGES,
					product.getImages().get(2).getFile_url());

			aq.id(iv_big)
					.image(url_thumb3, true, true, 0, R.drawable.icon_logo);
			}
			break;

		default:
			break;
		}
	}
}
